package cn.tyoui.analyzerImpl;

import cn.tyoui.Ianalyzer.IAnalysis;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.wltea.analyzer.lucene.IKAnalyzer;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 分词实现类
 *
 * @author Tyoui
 * @version 1.8.1
 */
public class AnalysisImpl implements IAnalysis {

    static Logger log= Logger.getLogger(AnalysisImpl.class);

    /**
     * 分词实现方法
     *
     * @param text        需要分析的句子
     * @param intelligent 是否启动智能切分
     * @return 分析后的集合
     */
    @Override
    public List<String> participle(String text, boolean intelligent) {
        List<String> list = new ArrayList<>();
        try {
            IKAnalyzer analyzer = new IKAnalyzer(intelligent);
            TokenStream tokenStream = analyzer.tokenStream("title", text);
            tokenStream.addAttribute(CharTermAttribute.class);
            tokenStream.reset();
            while (tokenStream.incrementToken()) {
                CharTermAttribute termAttribute = tokenStream.getAttribute(CharTermAttribute.class);
                String work = termAttribute.toString();
                if (work.length() > 1)
                    list.add(work);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return list;
    }

    /**
     * 网页与服务端的socket通讯
     *
     * @param socket socket对象
     * @return 通讯数据
     * @throws Exception 通讯失败
     */
    @Override
    public String socket(Socket socket) throws Exception {
        log.info("连接已建立。端口号：" + socket.getPort());
        Scanner scanner = new Scanner(socket.getInputStream());
        String text = "";
        if (scanner.hasNext()) {
            text = scanner.nextLine();
        }
        return text;
    }

    /**
     * 将分析好的数据发向浏览器
     *
     * @param socket socket对象
     * @param text   发送的信息
     * @throws Exception 发送失败
     */
    @Override
    public void sendMessageURL(Socket socket, String text) throws Exception {
        PrintStream out = null;
        try {
            out = new PrintStream(socket.getOutputStream());
            out.println("HTTP/1.1 200 OK");
            out.println("Content-type: application/json;");
            out.println();
            out.println(text);
            out.flush();
        } catch (Exception e) {
            log.info(e.getMessage());
        } finally {
            if (out != null)
                out.close();
            if (socket != null)
                socket.close();
        }
    }
}
